package com.ruoyi.web.controller.base.pc;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.po.EmpInfo;
import com.ruoyi.system.domain.request.EmpInfoReq;
import com.ruoyi.system.domain.request.JsonData;
import com.ruoyi.system.domain.request.MpSendMsgReq;
import com.ruoyi.system.domain.request.NTopn;
import com.ruoyi.system.domain.valid.BasicParameter;
import com.ruoyi.system.service.AddUserService;
import com.ruoyi.system.service.IRedisOperation;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class PersonHelper {


    private static final Logger log = LoggerFactory.getLogger(PersonHelper.class);
    @Autowired
    private IRedisOperation redisOperation = SpringUtils.getBean(IRedisOperation.class);


    public boolean check(HttpServletRequest request) {
        String json = request.getParameter("json");
        JsonData detail = new Gson().fromJson(json, JsonData.class);
        if (detail.getData() == null) {
            System.out.println("**************->>>>>>>>>>>>>>>>>data没数据");
            return false;
        }
        if (detail.getData().getEvents_type() == null) {
            System.out.println("**************->>>>>>>>>>>>>>>>>getEvents_type没数据");
            return false;
        }
        String typeCode = detail.getData().getEvents_type();
        System.out.println("Events_type:" + typeCode);
        if (!typeCode.equals("385") && !typeCode.equals("387")
                && !typeCode.equals("388") && !typeCode.equals("389")
                && !typeCode.equals("390") && !typeCode.equals("391")
                && !typeCode.equals("392") && !typeCode.equals("395")
                && !typeCode.equals("396") && !typeCode.equals("401")
                && !typeCode.equals("403") && !typeCode.equals("641")
                && !typeCode.equals("642") && !typeCode.equals("644")
                && !typeCode.equals("646")
        ) {
            System.out.println("**************->>>>>>>>>>>>>>>>>非限定告警类型过滤掉");
            return false;
        }
        return true;
    }


    public void handleVideoUpload(HttpServletRequest request) {
        String json = request.getParameter("json");
        JsonData detail = new Gson().fromJson(json, JsonData.class);

        // 检查请求是否是多部分
        if (ServletFileUpload.isMultipartContent(request)) {
            try {

//                String filePath = "/media/yasuo/9723f2a1-b4cc-4f10-a409-4280dd81b7d1/pic/" + detail.getData().getSnap_id() + ".jpg";
//                String newPath = "C:/testPath/";
                String filePath = BasicParameter.IMG_STORAGE_ADDRESS + detail.getData().getSnap_id() + ".jpg"; // 更改为本地照片文件的路径
                // 创建一个临时文件来存储视频数据
//                File tempFile = File.createTempFile("video_", ".png");
//                tempFile.deleteOnExit(); // 确保虚拟机退出时删除临时文件

                // 获取请求的输入流
                InputStream inputStream = request.getPart("snap").getInputStream();

                // 创建文件输出流
//                OutputStream outputStream = new FileOutputStream(tempFile);
                OutputStream outputStream = new FileOutputStream(filePath);

                // 缓冲区
                byte[] buffer = new byte[1024];
                int length;

                // 从输入流读取数据并写入文件
                while ((length = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, length);
                }

                // 关闭流
                outputStream.close();
                inputStream.close();

                // 处理视频文件，比如保存到永久存储位置
//                processVideoFile(tempFile);

            } catch (Exception e) {
                e.printStackTrace();

                System.out.println("**************->>>>>>>>>>>>>>>>>报错异常->>>>>>>>>" + e.getMessage());

            }
        }
    }


    private String getType(String typeCode) {
        String type;
        switch (typeCode) {
            case "389":
                type = "calling";
                break;
            case "387":
                type = "smoking";
                break;
            case "391":
                type = "clothes";
                break;
            default:
                type = "know";
                break;
        }
        return type;
    }

    /**
     * 上传文件到服务器
     *
     * @param targetURL
     * @param filePath
     */
    public void uploadFile(String targetURL, String filePath) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(targetURL);
            File file = new File(filePath);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                String responseString = EntityUtils.toString(responseEntity);
                System.out.println("Response: " + responseString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取session
     *
     * @return
     */
    public String getSession() {
        String urlString = "https://" + BasicParameter.AIEIP + "/api/json";
        String requestBody = "{\"user_name\":\"admin\",\"user_pwd\":\"admin123!\",\"msg_id\":\"257\"}";

        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                // 输出响应内容
                System.out.println(response.toString());
                // 解析响应内容
                String data = parseData(response.toString());
                System.out.println("Data: " + data);
                return data;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    private String parseData(String jsonResponse) {
        try {
            JSONObject jsonObject = new JSONObject(jsonResponse);
            return jsonObject.optString("data", null); // 使用 optString 来避免 JSONException
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取人像库id
     *
     * @return
     */
    public String callBackendService() {
        // 在与 HTTPS 服务交互之前配置自定义的 SSLContext
        SSLContextConfigurator.configure();


        String urlString = "https://" + BasicParameter.AIEIP + "/api/json";
        String requestBody = "{\"msg_id\":\"1028\"}";
        String sessionid = getSession();
//        String sessionid = redisOperation.getValue("sessionid");
//        //session 判断session
//        if (sessionid == null || sessionid.isEmpty()) {
//            // session为空或已过期，需要重新获取session
//            sessionid = getSession();
//            // 存储新的session到Redis，并设置过期时间（例如1分钟）
//            redisOperation.setValue("sessionid",sessionid, 1L, TimeUnit.MINUTES);
//        }


        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("sessionid", sessionid);
            conn.setDoOutput(true);

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                // 输出响应内容
                System.out.println(response.toString());
                // 解析响应内容并返回 lib_id 字符串
                return parseLibIds(response.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String parseLibIds(String jsonResponse) {
        try {
            JSONObject jsonObject = new JSONObject(jsonResponse);
            JSONArray dataArray = jsonObject.getJSONArray("data");
            // 使用 StringBuilder 来构建最终的字符串
            StringBuilder libIdsBuilder = new StringBuilder();

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject dataObject = dataArray.getJSONObject(i);
                String libId = String.valueOf(dataObject.optInt("lib_id"));

                libIdsBuilder.append(libId);
                // 在每个 lib_id 后加上逗号，除了最后一个
                if (i < dataArray.length() - 1) {
                    libIdsBuilder.append(",");
                }
            }

            return libIdsBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 人像库识别(1:N)
     *
     * @param libIds
     * @param imgFilePath
     * @return
     */
    public NTopn sendFormData(String libIds, String imgFilePath) {
        SSLContextConfigurator.configure();
        String targetURL = "https://" + BasicParameter.AIEIP + "/api/form";
        String sessionToken = getSession();
//        String sessionToken = redisOperation.getValue("sessionid");
//        //session 判断session
//        if (sessionToken == null || sessionToken.isEmpty()) {
//            // session为空或已过期，需要重新获取session
//            sessionToken = getSession();
//            // 存储新的session到Redis，并设置过期时间（例如5分钟）
//            redisOperation.setValue("sessionid",sessionToken, 5L, TimeUnit.MINUTES);
//        }
        // 1. 创建HttpRequest对象 - 指定好 url 地址
        HttpRequest httpRequest = new HttpRequest(targetURL);
        // 2. 设置请求方式，默认是GET请求
        httpRequest.setMethod(Method.POST);
        // 3. 设置请求参数 可通过 form表单方法 设置   可以是文件类型
        //    form方法有很多重载方法,可以一个一个参数设置，也可以将参数封装进一个map集合然后一块儿
        File file = new File(imgFilePath);
        httpRequest.form("msg_id", "772");
        httpRequest.form("threshold", "");
        httpRequest.form("img", file);
        httpRequest.form("lib_ids", libIds);
        // 4. 设置请求头
        //    请求头同样可以逐一设置，也可以封装到map中再统一设置
        //    设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
        httpRequest.header("sessionid", sessionToken); // 添加Session Token到Header
        httpRequest.header("Content-Type", "multipart/form-data; boundary=---Boundary");
        httpRequest.header("Connection", "keep-alive");
        httpRequest.header("Cache-Control", "no-cache");
        httpRequest.header("Accept-Encoding", "gzip, deflate, br");


        // 5. 执行请求，得到http响应类
        HttpResponse execute = httpRequest.execute();

        // 6. 解析这个http响应类，可以获取到响应主体、cookie、是否请求成功等信息
        boolean ok = execute.isOk(); // 是否请求成功 判断依据为：状态码范围在200~299内
        System.out.println(ok);
        List<HttpCookie> cookies = execute.getCookies();// 获取所有cookie
        cookies.forEach(System.out::println); // 如果为空不会遍历的
        String body = execute.body();   // 获取响应主体
        System.out.println(body);
        return parseNTopn(body);
    }


    /**
     * 单张人脸图片入库
     *
     * @param libIds
     * @param imgFilePath
     * @return
     */
    public Boolean addArchives(String libIds, String imgFilePath, String imgId, String name) {
        SSLContextConfigurator.configure();
        String targetURL = "https://" + BasicParameter.AIEIP + "/api/form";
        String sessionToken = getSession();
        // 1. 创建HttpRequest对象 - 指定好 url 地址
        HttpRequest httpRequest = new HttpRequest(targetURL);
        // 2. 设置请求方式，默认是GET请求
        httpRequest.setMethod(Method.POST);
        // 3. 设置请求参数 可通过 form表单方法 设置   可以是文件类型
        //    form方法有很多重载方法,可以一个一个参数设置，也可以将参数封装进一个map集合然后一块儿
        File file = new File(imgFilePath);
        httpRequest.form("msg_id", "1029");
        httpRequest.form("lib_id", libIds);
        httpRequest.form("img", file);
        httpRequest.form("img_id", imgId);
        httpRequest.form("person_name", name);
        // 4. 设置请求头
        //    请求头同样可以逐一设置，也可以封装到map中再统一设置
        //    设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
        httpRequest.header("sessionid", sessionToken); // 添加Session Token到Header
        httpRequest.header("Content-Type", "multipart/form-data; boundary=---Boundary");
        httpRequest.header("Connection", "keep-alive");
        httpRequest.header("Cache-Control", "no-cache");
        httpRequest.header("Accept-Encoding", "gzip, deflate, br");


        // 5. 执行请求，得到http响应类
        HttpResponse execute = httpRequest.execute();

        // 6. 解析这个http响应类，可以获取到响应主体、cookie、是否请求成功等信息
        return execute.isOk(); // 是否请求成功 判断依据为：状态码范围在200~299内
    }


    public NTopn sendMultipartFormDataPostRequest(String libIds, String imgFilePath, String imgFileName) {
        String targetURL = "https://" + BasicParameter.AIEIP + "/api/form";
        String msgId = "772";
        String threshold = "";
//        String sessionToken = getSession();
        String sessionToken = redisOperation.getValue("sessionid");
        //session 判断session
        if (sessionToken == null || sessionToken.isEmpty()) {
            // session为空或已过期，需要重新获取session
            sessionToken = getSession();
            // 存储新的session到Redis，并设置过期时间（例如5分钟）
            redisOperation.setValue("sessionid", sessionToken, 5L, TimeUnit.MINUTES);
        }
        try {
            URL url = new URL(targetURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("sessionid", sessionToken); // 添加Session Token到Header
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---Boundary");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");

            // 使用multipart/form-data格式发送表单数据
            try (OutputStream outputStream = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);) {
                writer.append("-----Boundary\r\n").flush();
                writer.append("Content-Disposition: form-data; name=\"msg_id\"\r\n\r\n").flush();
                writer.append(msgId + "\r\n---Boundary\r\n").flush(); // msg_id的值

                writer.append("Content-Disposition: form-data; name=\"threshold\"\r\n\r\n").flush();
                writer.append(threshold + "\r\n---Boundary\r\n").flush(); // threshold的值

                // 发送图片文件
                writer.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + imgFileName + "\"\r\n").flush();
                writer.append("Content-Type: image/jpeg\r\n\r\n").flush();
                try (BufferedInputStream fileStream = new BufferedInputStream(new FileInputStream(imgFilePath))) {
                    int bytesRead;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = fileStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
                writer.append("\r\n---Boundary\r\n").flush();

                writer.append("Content-Disposition: form-data; name=\"lib_ids\"\r\n\r\n").flush();
                writer.append(libIds + "\r\n---Boundary--\r\n").flush(); // lib_ids的值
            }

            // 读取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return parseNTopn(response.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static NTopn parseNTopn(String jsonResponse) {
        try {
            JSONObject responseJson = new JSONObject(jsonResponse);
            if (responseJson.getInt("code") == 0) {
                JSONObject dataObject = responseJson.getJSONObject("data");
                JSONObject nTopnJson = dataObject.optJSONObject("n_topn"); // 使用 optJSONObject 避免 JSONException
                if (nTopnJson != null && nTopnJson.optInt("similarity") >= 85) {
                    NTopn nTopn = new NTopn();
                    nTopn.setAddress(nTopnJson.optString("address"));
                    nTopn.setAge(nTopnJson.optString("age"));
                    nTopn.setGender(nTopnJson.optString("gender"));
                    nTopn.setId(nTopnJson.optString("id"));
                    nTopn.setImg_id(nTopnJson.optString("img_id"));
                    nTopn.setImg_path(nTopnJson.optString("img_path"));
                    nTopn.setLib_id(nTopnJson.optInt("lib_id"));
                    nTopn.setLib_name(nTopnJson.optString("lib_name"));
                    nTopn.setLib_type(nTopnJson.optInt("lib_type"));
                    nTopn.setName(nTopnJson.optString("name"));
                    nTopn.setRanking(nTopnJson.optInt("ranking"));
                    nTopn.setSimilarity(nTopnJson.optInt("similarity"));
                    nTopn.setWanderdeviceId(nTopnJson.optString("wanderdeviceid"));
                    nTopn.setWandertrigger(nTopnJson.optString("wandertrigger"));
                    return nTopn;
                } else {
                    System.out.println("n_topn object not found in the response.");
                }
            } else {
                System.out.println("Error in response: " + responseJson.getString("msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public void sendMsg(MpSendMsgReq req) {
        log.info("开始发送公众号消息====》");
        try {
            // 构建 JSON 对象
            JSONObject json = new JSONObject();
            json.put("trigger", req.getTrigger());
            json.put("alarmArea", req.getAlarmArea());
            json.put("eventsType", req.getEventsType());
            json.put("name", req.getName());
            json.put("state", req.getState());
            json.put("id", req.getId());

            // 目标 URL
            URL url = new URL("http://117.83.108.4:8093/msg/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            // 发送 JSON 数据
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = json.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response.toString());
            }

            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 处理自动添加人员入库
     */
    public void addUserHelper(EmpInfoReq req, MultipartFile file, AddUserService addUserService) {
        EmpInfo empInfo = new EmpInfo();
        BeanUtils.copyProperties(req, empInfo);
        //设置年纪
        if (empInfo.getEmpCard() != null && !empInfo.getEmpCard().isEmpty()) {
            empInfo.setEmpAge(getAgeFromIdCard(empInfo.getEmpCard()));
        }
        //图片名称设置为人员id
        empInfo.setEmpImg(req.getEmpId());
        addUserService.save(empInfo);
        File f = convertMultipartFileToFile(file);
        addUserToAIE(f, empInfo.getEmpId(), empInfo.getEmpName(), empInfo.getEmpSex(), empInfo.getEmpAge());


    }

    private File convertMultipartFileToFile(MultipartFile multipartFile) {
        try {
            File file = File.createTempFile("temp", multipartFile.getOriginalFilename());
            multipartFile.transferTo(file);
            return file;
        } catch (Exception e) {

        }
        return null;
    }

    public static int getAgeFromIdCard(String idCardNumber) {
        if (idCardNumber.length() == 18) {
            // 提取身份证中的出生日期部分
            String birthDateStr = idCardNumber.substring(6, 14);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
            LocalDate currentDate = LocalDate.now();
            // 计算年龄
            Period period = Period.between(birthDate, currentDate);
            return period.getYears();
        } else {
            throw new IllegalArgumentException("无效的身份证号码格式");
        }
    }

    /**
     * 将人员插入aie
     */
    public Boolean addUserToAIE(File file, String userID, String cardId, String sexStr, int age) {
        SSLContextConfigurator.configure();
        String targetURL = "https://" + BasicParameter.AIEIP + "/api/form";
        String sessionToken = getSession();
        // 1. 创建HttpRequest对象 - 指定好 url 地址
        HttpRequest httpRequest = new HttpRequest(targetURL);
        // 2. 设置请求方式，默认是GET请求
        httpRequest.setMethod(Method.POST);
        // 3. 设置请求参数 可通过 form表单方法 设置   可以是文件类型
        //    form方法有很多重载方法,可以一个一个参数设置，也可以将参数封装进一个map集合然后一块儿

        httpRequest.form("msg_id", "1029");
        //正式库为3 测试库为4
        httpRequest.form("lib_id", 3);
        httpRequest.form("img", file);
        httpRequest.form("img_id", userID);
        httpRequest.form("person_name", userID);
        int sex;
        if (sexStr.equals("00")) {
            sex = 1;
        } else {
            sex = 0;
        }
        httpRequest.form("person_gender", sex);
        if (age != 0) {
            httpRequest.form("person_age", age);
        }
        if (cardId != null && !cardId.isEmpty()) {
            httpRequest.form("person_idcard", cardId);
        }

        // 4. 设置请求头
        //    请求头同样可以逐一设置，也可以封装到map中再统一设置
        //    设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
        httpRequest.header("sessionid", sessionToken); // 添加Session Token到Header
        httpRequest.header("Content-Type", "multipart/form-data; boundary=---Boundary");
        httpRequest.header("Connection", "keep-alive");
        httpRequest.header("Cache-Control", "no-cache");
        httpRequest.header("Accept-Encoding", "gzip, deflate, br");


        // 5. 执行请求，得到http响应类
        HttpResponse execute = httpRequest.execute();

        // 6. 解析这个http响应类，可以获取到响应主体、cookie、是否请求成功等信息
        return execute.isOk(); // 是否请求成功 判断依据为：状态码范围在200~299内
    }


    /**
     * 根据头像获取评分
     */
    public int getFaceCore(String imgFilePath) {
        SSLContextConfigurator.configure();
        String targetURL = "https://" + BasicParameter.AIEIP + "/api/form";
        String sessionToken = getSession();
        // 1. 创建HttpRequest对象 - 指定好 url 地址
        HttpRequest httpRequest = new HttpRequest(targetURL);
        // 2. 设置请求方式，默认是GET请求
        httpRequest.setMethod(Method.POST);
        // 3. 设置请求参数 可通过 form表单方法 设置   可以是文件类型
        //    form方法有很多重载方法,可以一个一个参数设置，也可以将参数封装进一个map集合然后一块儿
        File file = new File(imgFilePath);
        httpRequest.form("msg_id", "769");
        httpRequest.form("img", file);
        // 4. 设置请求头
        //    请求头同样可以逐一设置，也可以封装到map中再统一设置
        //    设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
        httpRequest.header("sessionid", sessionToken); // 添加Session Token到Header
        httpRequest.header("Content-Type", "multipart/form-data; boundary=---Boundary");
        httpRequest.header("Connection", "keep-alive");
        httpRequest.header("Cache-Control", "no-cache");
        httpRequest.header("Accept-Encoding", "gzip, deflate, br");
        // 5. 执行请求，得到http响应类
        HttpResponse execute = httpRequest.execute();
        // 6. 解析这个http响应类，可以获取到响应主体、cookie、是否请求成功等信息
        boolean ok = execute.isOk(); // 是否请求成功 判断依据为：状态码范围在200~299内
        if (ok) {
            String jsonStr = execute.body();
            JSONObject responseJson = new JSONObject(jsonStr);
            if (responseJson.getInt("code") == 0) {
                JSONObject dataObject = responseJson.getJSONObject("data");
                return dataObject.getInt("quality");
            } else {
                System.out.println("Error in response: " + responseJson.getString("msg"));
            }
        }
        return -1;
    }

    public void alterPersonnel(String imgId,int libId) {
        log.info("开始修改人员库头像====》");
        try {
            // 构建 JSON 对象
            JSONObject json = new JSONObject();
            json.put("msg_id", "1033");
            json.put("img_id", imgId);
            json.put("lib_id", libId);


            // 目标 URL
            URL url = new URL("https://" + BasicParameter.AIEIP + "/api/json");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            // 发送 JSON 数据
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = json.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response.toString());
            }

            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
